#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# Check whether `docker` command requires sudo
if ! docker ps >/dev/null 2>/dev/null ; then
    USERNAME=$(whoami)

    ORCHEST_PATH=.
    # Check if orchest is in PWD
    if ! test -f "orchest"; then
        ORCHEST_PATH=$DIR
    fi

    # Automatically prepending with `sudo` makes sure this script does
    # not have to be run using `sudo`, which would overwrite the `$USER`
    # variable and thereby writing the `HOST_CONFIG_DIR` to the wrong
    # location.
    echo "'docker' is not accessible for the current user: '$USERNAME'"
    echo "Automatically prepending 'sudo' for 'docker' commands..."
    SUDO_PREFIX="sudo"
fi

function update_orchest_ctl {
    # Update orchest-ctl to latest before performing update
    $SUDO_PREFIX docker pull orchest/orchest-ctl:latest
}

# Before running an update, update the orchest-ctl as the latest
# orchest-ctl should be used to update the application.
[[ ( "$1" == "update" ) || ( "$1" =~ ^-v*$ && "$2" == "update" ) ]] && \
[[ "$@" != *"--help"* ]] && \
[[ "$@" != *"--dev"* ]] && \
update_orchest_ctl

HOST_CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/orchest"
HOST_USER_DIR=$DIR/userdir

# We detect the host OS to properly set the GID owner
# that is used for files in the userdir/
HOST_OS="linux"
if [[ "$OSTYPE" == "darwin"* ]]; then
    HOST_OS="darwin"
fi

# create config dir if it doesn't exist
mkdir -p "${HOST_CONFIG_DIR}"
$SUDO_PREFIX chown $USER "${HOST_CONFIG_DIR}"

# The -it flags are needed to be able to safely prompt for secrets
# (password and tokens) when adding a new user. The -i is actually
# needed for prompting, while the -t is to make it safe, without the -t
# getpass would complain.

OPTIONAL_IT=""
if [ "$1" == "adduser" ] && [ -t 1 ]
then
    OPTIONAL_IT="-it"
fi


$SUDO_PREFIX docker run \
    --rm \
    ${OPTIONAL_IT} \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v "${DIR}":/orchest-host \
    -v "${HOST_CONFIG_DIR}":/config \
    -e HOST_CONFIG_DIR="${HOST_CONFIG_DIR}" \
    -e HOST_REPO_DIR="${DIR}" \
    -e HOST_USER_DIR="${HOST_USER_DIR}" \
    -e HOST_OS="${HOST_OS}" \
    orchest/orchest-ctl:latest "$@"
